import common from '@/utils/open/common'
import api from '@/api'
import constant from '@/constant'
import validate from '@/utils/open/validate'
import { Encrypt, Decrypt } from '@/utils/open/secret'
import vuxTool from '@/utils/open/vux-plugin'
import md5 from 'js-md5'
import store from '@/store'

/**
 * 针对获取数据进行二次数据清洗、加工、转化，特别指API
 */
export default {
  // 对登录信息进行处理
  login(name, pwd, loginType) {
    loginType = loginType || 2
    return new Promise((resolve, reject) => {
      // debugger
      let params = {}
      if (!name) {
        params = common.getLocalCache('userAccount') || {}
        if (!validate.isNull(params)) {
          params = Decrypt(params)
          params = JSON.parse(params)
        }
      } else {
        params = {
          name: name, // 登陆账户名或手机号
          pwd: common.jsEncryptCode(md5(pwd)) // 登陆密码（经过md5处理过的）
        }
      }
      // debugger
      params.captcha = common.getTokenUuid()
      if (!params.name) {
        if (loginType === 2) {
          resolve({ loginStatus: false })
        } else {
          vuxTool.errorMsg('登陆失败，账号不能为空！')
        }
        return
      }

      if (!params.pwd) {
        if (loginType === 2) {
          resolve({ loginStatus: false })
        } else {
          vuxTool.errorMsg('登陆失败，密码不能为空！')
        }
        return
      }
      // debugger
      api.user.login(params).then((res) => {
        // debugger
        res.loginStatus = true
        const data = res.result
        common.setKeyVal('user', 'token', data.accessToken, 'sessionStorage')
        common.setKeyVal('user', 'refreshToken', data.refreshToken, 'sessionStorage')
        common.setKeyVal('user', 'isLogin', true)
        common.setLocalCache('userAccount', Encrypt(JSON.stringify(params).toString()))
        resolve(res)
      }).catch(error => {
        common.clearAccountFn() // 清空用户账户数据
        reject(error)
      })
    })
  },
  // 对单位列表信息进行处理
  getUnitList() {
    return new Promise((resolve, reject) => {
      api.user.getUnitList().then((unitList) => {
        // console.log(unitList, 'res')
        const dataArr = unitList.result || []
        if (dataArr.length > 0) {
          for (const obj of dataArr) {
            obj.select = false
            // debugger
            if (obj.logo && obj.logo.indexOf('http') <= -1) {
              obj.logo = constant.file_ctx + obj.logo
            }
          }
          // debugger
          let curSelectUnit = {}
          let flag = false
          const urlParam = common.getKeyVal('user', 'firstUrlParam', 'sessionStorage') || {}

          if (urlParam.recordId && urlParam.unitId) { // 1.首先考虑链接传参 unitId(在有recordId前提下生效，这里的recordId是员工档案id，学生监护人档案id)
            for (const obj of dataArr) {
              if (obj.unitId === urlParam.unitId) {
                obj.select = true
                curSelectUnit = obj
                flag = true
                urlParam.unitId = null
                common.setKeyVal('user', 'firstUrlParam', urlParam, 'sessionStorage') // 只使用一次，用完就删，保证下次刷新
                break
              }
            }
          }
          if (!flag) { // 2.再考虑缓存
            const curSelectUnitId = common.getKeyVal('user', 'curSelectUnitId', 'localStorage')
            for (const obj of dataArr) {
              if (obj.unitId === curSelectUnitId) {
                obj.select = true
                curSelectUnit = obj
                flag = true
                break
              }
            }

            if (!flag) { // 3.最后考虑默认单位
              for (const obj of dataArr) {
                if (obj.isDefault === '1436') {
                  obj.select = true
                  curSelectUnit = obj
                  break
                }
              }
            }
          }

          common.setKeyVal('user', 'unitList', dataArr)
          common.setKeyVal('user', 'curSelectUnit', curSelectUnit)
          common.setKeyVal('user', 'curSelectUnitId', curSelectUnit.unitId, 'localStorage')
          resolve(unitList)
        } else {
          common.setKeyVal('user', 'unitList', [])
          resolve(unitList)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 查找对应的单位信息
  changeUnit(id) {
    vuxTool.loading('正在切换')
    return new Promise((resolve, reject) => {
      // debugger
      if (!id) {
        const curSelectUnitId = common.getKeyVal('user', 'curSelectUnitId', 'localStorage')
        if (!curSelectUnitId) {
          const unitList = common.getKeyVal('user', 'unitList')
          for (const obj of unitList) {
            if (obj.isDefault === '1436') {
              id = obj.unitId
              break
            }
          }
        } else {
          id = curSelectUnitId
        }
      }
      if (!id) {
        reject()
        return
      }
      const params = {
        id: id // 单位主键id
      }
      params.captcha = common.getTokenUuid()
      api.user.changeUnit(params).then((res) => {
        common.setKeyVal('user', 'curSelectUnitId', id, 'localStorage')
        // debugger
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 对用户信息进行处理
  getUserInfo() {
    return new Promise((resolve, reject) => {
      api.user.getUserInfo().then((userInfo) => {
        let curSelectRole = {}
        const userList = userInfo.data || []
        // 判断档案数据是否为空
        if (userList.length > 0) {
          for (const obj of userList) {
            // 获取用户性别icon
            if (obj.headImage && obj.headImage.indexOf('http') <= -1) {
              obj.headImage = constant.file_ctx + obj.headImage
            } else {
              // console.log('getUserInfo-用户头像为空')
            }
            common.getDefaultHeadImage(obj)
          }
          // debugger
          const urlParam = common.getKeyVal('user', 'firstUrlParam', 'sessionStorage') || {}
          // /staff/notice/notice-detail?index=0&id=344539241079898112&recordId=343012457955983360&openId=omZ3l1BDObB4Q6OXQT6J8URYaz9I&appId=wx2cd3a98f3ec208a7&unitId=315971766105145344
          // 设置默认选中角色
          const curSelectRoleId = common.getKeyVal('user', 'curSelectRoleId', 'localStorage')

          if (urlParam.recordId) { // 1. 从推送链接进来，若带参 record
            for (const obj of userList) {
              let id = obj.id
              if (obj.identityType === '1538') { // 员工与家长返回 档案id 不一样，需要如此判断
                id = obj.guardianId
              }
              if (urlParam.recordId === id) {
                obj.select = true
                curSelectRole = obj
                urlParam.recordId = null
                common.setKeyVal('user', 'firstUrlParam', urlParam, 'sessionStorage') // 只使用一次，用完就删，保证下次刷新
              } else {
                obj.select = false
              }
            }

            if (!curSelectRole.id) { // 若传参id没能对应上，则默认使用第一个
              userList[0].select = true
              curSelectRole = userList[0]
            }
          } else if (!validate.isNull(curSelectRoleId)) { // 2. 若本地存在上一次操作的角色id，若匹配不上，则默认使用第一个
            for (const obj of userList) {
              if (obj.id === curSelectRoleId) {
                obj.select = true
                curSelectRole = obj
                // debugger
              } else {
                obj.select = false
              }
            }
            // 匹配不上，则采用第一个角色（切换单位后）(在有职工账号前提下，第一个账号永远为职工)
            if (validate.isNull(curSelectRole)) {
              userList[0].select = true
              curSelectRole = userList[0]
            }
          } else { // 3.本地没有缓存，则使用第一个后台返回select为true的那个
            for (const obj of userList) {
              if (obj.select) {
                curSelectRole = obj
                break
              }
            }
          }
          userInfo.data = userList
          const info = userInfo
          common.setKeyVal('user', 'userInfo', info)
          resolve(curSelectRole)
        } else {
          curSelectRole = {}
          common.getDefaultHeadImage(curSelectRole)
          common.setKeyVal('user', 'userInfo', userInfo)
          resolve(userInfo)
        }
        common.setKeyVal('user', 'curSelectRole', curSelectRole)
        common.setKeyVal('user', 'curSelectRoleId', curSelectRole.id, 'localStorage')
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 重新请求票据
  timingChangeToken() {
    // debugger
    let tiemr = store.state.sys.timerChangeToken
    const token = common.getToken()
    if (!token && tiemr) {
      return
    }
    // debugger
    tiemr = setInterval(() => {
      console.log('定时刷新token')
      const params = {
        // captcha: common.uuid()
        refreshToken: common.getKeyVal('user', 'refreshToken', 'sessionStorage')
      }

      api.user.timingChangeToken(params).then((res) => {
        const data = res.result
        // debugger
        common.setKeyVal('user', 'token', data.accessToken, 'sessionStorage')
        common.setKeyVal('user', 'refreshToken', data.refreshToken, 'sessionStorage')
      }).catch(e => {})
    }, 25 * 60 * 1000)
    store.dispatch('sys/UpdateTimerChangeToken', tiemr)
  },
  /**
   * 获得临时token
   */
  getToken() {
    return new Promise((resolve, reject) => {
      const stam = +new Date()
      const encrypted = 'Vb8Uk9N&Q2*zDbx$' + stam
      const params = {
        captcha: common.getTokenUuid(),
        timestamp: stam, // 当前的时间戳
        encrypted: md5(encrypted) // 密文（经过md5处理过的）
      }
      api.user.getToken(params).then((res) => {
        // const token = res.result
        const data = res.result
        // debugger
        // common.setKeyVal('user', 'token', token, 'sessionStorage')
        // debugger
        common.setKeyVal('user', 'token', data.accessToken, 'sessionStorage')
        common.setKeyVal('user', 'refreshToken', data.refreshToken, 'sessionStorage')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getCodeUserInfo() {
    return new Promise((resolve, reject) => {
      api.user.getCodeUserInfo().then((res) => {
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  }
}
